<template>
  <AdminHeader />
  <div>
    <div class="container-fluid">
      <div class="row text-center justify-content-center webtitle">管理员添加用户</div>
      <div class="row justify-content-center">
        <el-form ref="novelForm" :rules="rules" :model="form" label-width="auto" @submit.prevent="addUser" style="max-width: 400px">

          <el-form-item label="用户名" prop="username" required>
            <el-input v-model="form.username" required clearable></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" clearable required></el-input>
          </el-form-item>
          <el-form-item class="text-center" style="width: 100%">
            <el-button type="primary" native-type="submit" style="width: 120px; margin: 0 auto;">添加用户</el-button>
          </el-form-item>
          <el-form-item class="text-center" style="width: 100%">
            <el-button @click="goBack" style="width: 120px; margin: 0 auto;">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {useRouter} from 'vue-router';
import axios from 'axios';
import {ElNotification} from "element-plus";
import AdminHeader from "@/components/AdminHeader.vue";
import VueCookies from "vue-cookies";
import config from "../../../config/config.js";

VueCookies.set('activeIndex', 2);
const form = ref({
  username: '',
  password: '123456',
});

const errorMessage = ref(''); // 错误消息
const router = useRouter();
const rules = {
  username: [
    {required: true, message: '用户名必填', trigger: 'blur'},
    // 其他验证规则
  ],
  password: [
    {required: true, message: '密码必填', trigger: 'blur'},
    // 其他验证规则
  ],
};
const addUser = async () => {
  try {
    // 发送 POST 请求
    const response = await axios.post(`${config.apiUrl}/user/register`, {
      username: form.value.username,
      password: form.value.password,
    });

    if (response.status === 200) {
      form.value.username = '';
      form.value.password = '123456';
      showNotification("添加用户成功！","success");
    } else {
      errorMessage.value = response.data.message || '添加用户失败！'; // 设置错误消息
      showNotification(errorMessage,"error");
    }
  } catch (error) {
    errorMessage.value = '添加用户失败！未知原因！'; // 错误消息
    showNotification(errorMessage,"error");
  }
};
const showNotification = (tips,type) => {
  ElNotification({
    message: tips, // 消息内容
    type: type,
    duration: 1500, // 消息显示的持续时间
  });
};
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.webtitle {
  font-size: 18px;
  letter-spacing: 2px;
  padding: 20px;
}
</style>
